﻿using Microsoft.EntityFrameworkCore;
using PublicCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using T_Person.Domain;

namespace T_Person.BaseRep
{
    public class BaseWays<T> : IBaseRepInterface<T> where T : class
    {
        private readonly Mycreate Mycreate;

        public BaseWays(Mycreate mycreate)
        {
            Mycreate = mycreate;
        }
        /// <summary>
        /// 异步添加方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> Add(T model)
        {
            DbSet<T> db=Mycreate.Set<T>();
            await db.AddAsync(model);
            return await Mycreate.SaveChangesAsync();
        }
        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> Delete(T model)
        {
           DbSet<T>db=Mycreate.Set<T>();
           db.Remove(model);
          return await Mycreate.SaveChangesAsync();
        }
        /// <summary>
        /// 批量删除方法
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public async Task<int> DeleteRange(List<T> values)
        {
            Mycreate.Set<T>().RemoveRange(values);
            return await Mycreate.SaveChangesAsync();
        }

        /// <summary>
        /// 通过主键获取单一数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetAloneByid(int id)
        {
            return await Mycreate.Set<T>().FindAsync(id);
        }

        public async Task<T> GetAloneByresult(Expression<Func<T, bool>> result)
        {
                
          return await Mycreate.Set<T>().Where(result).AsNoTracking().FirstOrDefaultAsync();
        }

        public async Task<IQueryable<T>> Getvalues()
        {
            return await Task.FromResult(Mycreate.Set<T>().AsNoTracking().AsQueryable());
        }

        public async Task<IQueryable<T>> GetvaluesByResult(Expression<Func<T, bool>> result)
        {
            return await Task.FromResult(Mycreate.Set<T>().Where(result).AsNoTracking().AsQueryable());
        }

        public async Task<int> Update(T model)
        {
             Mycreate.Set<T>().Update(model);
            return await Mycreate.SaveChangesAsync();
        }

        public async Task<int> UpdateRange(List<T> values)
        {
            Mycreate.Set<T>().UpdateRange(values);
            return await Mycreate.SaveChangesAsync();
        }
    }
}
